package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.example.library_common.adapter.JssBaseQuickAdapter
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.BaseLazyDataBindingFragment
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.utils.PixUtils
import com.example.library_common.utils.QMUIDisplayHelper
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.GoodsNewDetailFragmentBinding
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.GoodsDetailLikeListBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods.widget.GoodsFolderLayoutToggleListener
import com.example.shushiyunsst.util.*
import com.example.shushiyunsst.util.extension.goneAlphaAnimation
import com.example.shushiyunsst.util.extension.visibleAlphaAnimation

@Route(path = GOODS_DETAIL)
class GoodsNewDetailFragment : BaseLazyDataBindingFragment<GoodsNewDetailFragmentBinding>(),
    View.OnClickListener, GoodsFolderLayoutToggleListener {

    var mViewModel: GoodsNewDetailViewModel? = null

    private val mGoodNewSelectPop = GoodsTypeSelectFragment.newInstance()

    @JvmField
    @Autowired(name = GOODS_ID)
    var categoryId: String = ""

    private var mGoodsPicsAdapter: JssBaseQuickAdapter<String>? = null

    private val pageSnap = LinearSnapHelper()

    private var mIntroduceGoodsAdapter: CommAdapter<String>? = null

    private var mGuessLikeAdapter: CommAdapter<GoodsDetailLikeListBean>? = null

    private val maxDistance = PixUtils.dp2px(240) * 1f

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = ViewModelProvider(this).get(GoodsNewDetailViewModel::class.java)
        mViewModel?.mCategoryId = categoryId
        mViewModel?.getLocalShopCarBean()

    }

    override fun layoutId(): Int {
        return R.layout.goods_new_detail_fragment
    }

    override fun initView(view: View) {
        viewBinder.lifecycleOwner = this

        viewBinder.vModel = mViewModel

        viewBinder.onViewClick = this

        viewBinder.mGoodsFolderLayout.setToggleListener(this)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            viewBinder.mScrollView.setOnScrollChangeListener { _, _, scrollY, _, _ ->

                val alpha = scrollY * 1f / maxDistance

                viewBinder.headerBg.alpha = if (alpha > 1f) 1f else alpha
            }
        }

        loadRootFragment(R.id.albumFolderPopupMenuViews, mGoodNewSelectPop)

        initGoodsPics()

        initIntroduceGoods()

        initGuessLike()

        mViewModel?.infoDaoLiveData?.observe(viewLifecycleOwner, {
            viewBinder?.mProgressBar?.goneAlphaAnimation()
            initData()
        })


    }

    override fun lazyInit() {
        viewBinder?.mProgressBar?.visibleAlphaAnimation()
        requestData()
    }

    private fun initData() {

        viewBinder.mScrollView.scrollTo(0, 0)

        mGoodNewSelectPop.setGoodsDetailBean(mViewModel?.infoDaoLiveData?.value)

        viewBinder.moneyTv.text = mViewModel?.moneyTvText()

        viewBinder.goodsOldPrice.text = mViewModel?.goodsOldPriceText()

        viewBinder.goodsStock.text = mViewModel?.goodsStockText()

        viewBinder.goodsSales.text = mViewModel?.goodsSalesText()

//        viewBinder.mCollectionsTv.isSelected =
//            mViewModel?.infoDaoLiveData?.value?.goods?.isCollected == true

        addGoodsPics()

        addIntroduceGoods()

        addGuessLikeAdapter()
    }

    private fun addGuessLikeAdapter() {
        mGuessLikeAdapter?.clear()

        val likeList = mViewModel?.infoDaoLiveData?.value?.likeList ?: emptyList()

        mGuessLikeAdapter?.addAll(likeList)
    }

    private fun addIntroduceGoods() {
        val goodsContentStr = mViewModel?.infoDaoLiveData?.value?.goods?.goodsContent ?: ""

        val goodsPics = JSON.parseObject(goodsContentStr)

        val pics = goodsPics["pics"] ?: return

        val array = JSON.parseArray(pics.toString())

        val ls = mutableListOf<String>()

        for (e in array.iterator()) {

            if (e is JSONObject) {

                val url = e["url"].toString()

                ls.add(url)
            }
        }
        mIntroduceGoodsAdapter?.clear()
        mIntroduceGoodsAdapter?.addAll(ls)
        viewBinder.mIntroduceGoods.maxItem = ls.size
    }

    private fun addGoodsPics() {
        val goodsPicsStr = mViewModel?.infoDaoLiveData?.value?.goods?.goodsPics ?: ""

        val goodsPics = JSON.parseObject(goodsPicsStr)

        val pics = goodsPics["pics"] ?: return

        val array = JSON.parseArray(pics.toString())

        val ls = mutableListOf<String>()

        for (e in array.iterator()) {

            if (e is JSONObject) {

                val url = e["url"].toString()

                ls.add(url)
            }
        }
        mGoodsPicsAdapter?.clears()
        mGoodsPicsAdapter?.addData(ls)
    }

    private fun requestData() = mViewModel?.getGoodsDetailInfo()

    private fun initGuessLike() {
        mGuessLikeAdapter =
            object : CommAdapter<GoodsDetailLikeListBean>(
                _mActivity, R.layout.goods_detail_guess_like
            ) {
                override fun convert(
                    holder: XQuickViewHolder?, item: GoodsDetailLikeListBean?, position: Int
                ) {
                    val givenCml = "${item?.givenCml}"
                    val giveCmlStr = _mActivity.getString(R.string.wallet_fu_li_scored)
                    holder?.setText(R.id.payedCount, giveCmlStr)
                        ?.setText(R.id.mGoodsPrice, "\$${item?.goodsPrice}")
                        ?.setText(R.id.goodsName, item?.goodsName)

                        ?.displayImage(
                            R.id.mGoodsPics,
                            item?.parseGoodsPics(),
                            R.mipmap.image_loading
                        )
                        ?.setOnClickListener {
                            categoryId = item?.gid.toString()
                            mViewModel?.mCategoryId = categoryId
                            requestData()
                        }
                }

            }
        viewBinder.mGuessLike.setAdapter(mGuessLikeAdapter, lifecycle)
    }

    private fun getRequestOptions()= RequestOptions()
        //注意: 对应的 ImageView 的裁切类型必须一致!!!
        .centerCrop()
        .dontAnimate()
        //使用透明图占位图, 无缝过渡效果更佳!!!
        .placeholder(R.mipmap.image_loading)
        .error(R.mipmap.image_loading)
        .skipMemoryCache(false)
        .diskCacheStrategy(DiskCacheStrategy.ALL)


    private fun initIntroduceGoods() {

        val screenWidth = QMUIDisplayHelper.getScreenWidth(_mActivity)
        mIntroduceGoodsAdapter =
            object : CommAdapter<String>(_mActivity, R.layout.goods_detail_introduce_goods) {
                override fun convert(holder: XQuickViewHolder?, item: String?, position: Int) {
                    val icon: ImageView? = holder?.getView(R.id.icon)
                    GlideApp.with(_mActivity)
                        .load(item)
                        .apply(getRequestOptions())
                        .transition(DrawableTransitionOptions.withCrossFade())
                        .into(object : CustomTarget<Drawable>() {
                            override fun onResourceReady(
                                resource: Drawable,
                                transition: Transition<in Drawable>?
                            ) {
                                val imgWidth = resource.intrinsicWidth
                                val imgHeight = resource.intrinsicHeight
                                val realHeight =
                                    screenWidth * imgHeight / imgWidth

                                if (icon != null) {
                                    GlideApp.with(_mActivity)
                                        .load(item)
                                        .override(screenWidth,realHeight)
                                        .placeholder(R.mipmap.image_loading)
                                        .into(icon)
                                }


                            }

                            override fun onLoadCleared(placeholder: Drawable?) {

                            }

                        })
//                    holder?.displayImage(R.id.icon, item,R.mipmap.image_loading,screenWidth)
                }

            }
        viewBinder.mIntroduceGoods.setAdapter(mIntroduceGoodsAdapter, lifecycle)
    }

    private fun initGoodsPics() {
        viewBinder.mGoodsPics.layoutManager =
            LinearLayoutManager(_mActivity, LinearLayoutManager.HORIZONTAL, false)
        mGoodsPicsAdapter = object : JssBaseQuickAdapter<String>(R.layout.goods_detail_pics) {

            override fun convert(holder: JssBaseViewHolder?, item: String?) {
                super.convert(holder, item)
                holder?.setImageNetUrl(R.id.icon, item, R.mipmap.image_loading)
            }
        }
        viewBinder.mGoodsPics.adapter = mGoodsPicsAdapter
        pageSnap.attachToRecyclerView(viewBinder.mGoodsPics)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.mPageBack -> {
                onBackPressedSupport()
            }

            R.id.carShop -> {
                ARouter.getInstance()
                    .build(SHOP_CAR)
                    .startNavigation(this)
            }

            R.id.mCollectionsTv -> {
                mViewModel?.collectionHandle()
            }
            R.id.mGoodSelect -> {
                viewBinder.mGoodsFolderLayout.toggle()
            }
            R.id.goodsComment -> {
                val infoDao = mViewModel?.infoDaoLiveData?.value
                ARouter.getInstance()
                    .build(GOODS_COMMENT)
                    .withString(GOODS_ID, infoDao?.goods?.gid.toString())
                    .startNavigation(this)
            }
            R.id.payingNow -> {
                if (mViewModel?.infoDaoLiveData?.value != null) {
                    start(ConfirmSingleTakeOrderFragment.newInstance(mViewModel?.infoDaoLiveData?.value))
                }

            }

            R.id.addShoppingCar -> {
                val infoDao = mViewModel?.infoDaoLiveData?.value
                if (infoDao?.goods?.selectedLabStr?.isNotEmpty() == true) {
                    mViewModel?.saveGoods(_mActivity)
                    return
                }
                viewBinder.mGoodsFolderLayout.toggle()
            }
        }
    }

    override fun onToggle() {
        if (!viewBinder.mGoodsFolderLayout.isOnShowIng()) {
            var selectedLab = ""
            mGoodNewSelectPop.mGoodsTypeAdapter?.data?.forEach {
                selectedLab += "${it.selectedItem?.name},"
            }

            if (selectedLab.indexOf(",") != selectedLab.lastIndexOf(",")) {
                selectedLab = selectedLab.substring(0, selectedLab.lastIndexOf(","))
            }

            val value = mGoodNewSelectPop.mViewModel?.infoDaoLiveData?.value
            value?.goods?.selectedGoodsType = selectedLab
            mViewModel?.infoDaoLiveData?.postValue(value)
        }
    }
}